package com.ato.mybatis.response;

import com.ato.mybatis.enums.RestStatusEnum;
import com.github.xiaoymin.knife4j.spring.annotations.EnableKnife4j;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
import springfox.documentation.spring.web.SpringfoxWebConfiguration;

import java.io.InputStream;
import java.net.InetSocketAddress;

/**
 * @author wangjing
 * @create 2021--09--27--下午 5:47
 */
@Slf4j
@Component
@RestControllerAdvice
public class ResponseHandler implements ResponseBodyAdvice<Object> {
    //    //这个方法表示对于哪些请求要执行beforeBodyWrite，返回true执行，返回false不执行
    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        return true;
    }

    @Override
    @ResponseBody
    public Object beforeBodyWrite(Object body, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest request, ServerHttpResponse response) {
        String path = request.getURI().getPath().toString().toLowerCase();
//  遍历，如果是kenife4j的请求走过滤掉，直接返回。
        String[] url = path.split("/api/");
        for (int i = 0; i < url.length; i++) {
//            System.out.println(url[i]);
            if (url[i].startsWith("swagger-resources") || url[i].startsWith("v2/api-docs")) {
                return body;
            }
        }
        //处理重复包装R
        if (body instanceof R) {
            return body;
        }
//        错误也会封装到这里，然后data里才是错误草。， 500 其实也是请求到了，只是服务器报错了。，而404 是完全找不到，都没有请求到，感觉这样也说得通
        return R.ok(body);
    }
}
